package cn.ucox.web.ms.service.impl;

import cn.ucox.web.ms.domain.ApiPager;
import cn.ucox.web.ms.domain.ApiQueryBase;
import cn.ucox.web.ms.monitor.SyncFileParser;
import cn.ucox.web.ms.polling.SyncAnchor;
import cn.ucox.web.ms.polling.SyncRedisUtil;
import cn.ucox.web.ms.redis.RedisClient;
import cn.ucox.web.ms.service.IMonitorService;
import cn.ucox.web.ms.view.ApiResult;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Tuple;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import static cn.ucox.web.ms.Constant.*;
import static cn.ucox.web.ms.monitor.FtpDirectoryListener.FTP_TRANS_DATA_TIMER;
import static cn.ucox.web.ms.monitor.SyncFileParser.SYNC_FTP_FILE_INDEX;

/**
 * Created by Administrator on 2017/9/4.
 */
@Component
public class MonitorServiceImpl implements IMonitorService{

    private RedisClient redisClient = RedisClient.instance();

    @Override
    public SyncAnchor getSyncAnchor() {
        SyncAnchor anchor = SyncRedisUtil.loadSyncAnchorFromRedis();

        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Calendar calendar = Calendar.getInstance();
        String dateStr = "";
        if(!anchor.getDataStartTime().equals("0")){
            calendar.setTimeInMillis(Long.valueOf(anchor.getDataStartTime().substring(0,anchor.getDataStartTime().indexOf("."))));
            dateStr = formatter.format(calendar.getTime());
            dateStr = dateStr + anchor.getDataStartTime().substring(anchor.getDataStartTime().indexOf("."));
            anchor.setDataStartTime(dateStr);
        }

        if(!anchor.getDataEndTime().equals("0")){
            calendar.setTimeInMillis(Long.valueOf(anchor.getDataEndTime().substring(0,anchor.getDataEndTime().indexOf("."))));
            dateStr = formatter.format(calendar.getTime());
            dateStr = dateStr + anchor.getDataEndTime().substring(anchor.getDataEndTime().indexOf("."));
            anchor.setDataEndTime(dateStr);
        }

        if(anchor.getSyncStartTime() != 0L){
            calendar.setTimeInMillis(anchor.getSyncStartTime());
            dateStr = formatter.format(calendar.getTime());
            anchor.setSyncStartTimeStr(dateStr);
        }

        if(anchor.getSyncEndTime() != 0L){
            calendar.setTimeInMillis(anchor.getSyncEndTime());
            dateStr = formatter.format(calendar.getTime());
            anchor.setSyncEndTimeStr(dateStr);
        }

        return anchor;
    }

    @Override
    public Map<String, String> getParseAnchor() {
        Map<String, String> anchor = redisClient.hgetAll(SyncFileParser.FTP_DATA_PARSE_ANCHOR);

        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();

        calendar.setTimeInMillis(Long.valueOf(anchor.get("startTime")));
        String dateStr = formatter.format(calendar.getTime());
        anchor.put("startTime",dateStr);
        return anchor;
    }

    @Override
    public ApiResult getLogParse(ApiQueryBase apiQueryBase) {
        long length = redisClient.llen(LOG_PARSE);
        int pageSize = apiQueryBase.getPageSize();
        int pageIndex = apiQueryBase.getPageIndex();
        List<String> list = redisClient.lrange(LOG_PARSE,(pageIndex-1)*pageSize,pageSize*pageIndex-1);
        ApiPager<List<String>> apiPager = new ApiPager(apiQueryBase.getPageSize(), apiQueryBase.getPageIndex(), length, list);
        return new ApiResult<ApiPager<List<String>>>().success("异常数据监控",apiPager);
    }

    @Override
    public ApiResult remLogParse(String value) {

        long result = redisClient.lrem(LOG_PARSE,1,value);
        if(result > 0){
            return new ApiResult<>().success("异常数据删除成功");
        }
        return new ApiResult<>().failure("异常数据删除失败");
    }

    @Override
    public ApiResult getDataBackup(ApiQueryBase apiQueryBase) {
        long length = redisClient.llen(SYNC_TRANS_RESULT_DATA_BACKUP);
        int pageSize = apiQueryBase.getPageSize();
        int pageIndex = apiQueryBase.getPageIndex();
        List<String> list = redisClient.lrange(SYNC_TRANS_RESULT_DATA_BACKUP,(pageIndex-1)*pageSize,pageSize*pageIndex-1);
        List<JSONObject> jsonObjectList = new ArrayList<>();
        for (String str : list){
            JSONObject object = JSONObject.parseObject(str);
            jsonObjectList.add(object);
        }

        ApiPager<List<JSONObject>> apiPager = new ApiPager(apiQueryBase.getPageSize(), apiQueryBase.getPageIndex(), length, jsonObjectList);
        return new ApiResult<ApiPager<List<JSONObject>>>().success("异常备份数据监控",apiPager);
    }

    @Override
    public Set<String> getDataAnchor() {
        return redisClient.keys("SYNC:FTP:DATA:ANCHOR:*");
    }

    @Override
    public Map<String, String> getDataAnchorDetail(String key) {
        Map<String, String> anchor = redisClient.hgetAll(key);

        return anchor;
    }

    @Override
    public JSONObject getMonitorFtp(int second) {
        Calendar calendar = Calendar.getInstance();
        long max = calendar.getTimeInMillis();

        calendar.add(Calendar.SECOND,-second);
        long min = calendar.getTimeInMillis();

        Set<Tuple> tupleSet = redisClient.zrangeByScoreWithScores(SYNC_MONITOR_FTP,min,max);

        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        JSONObject object = new JSONObject();
        int duration = 0;
        int transCount = 0;
        int dataLength = 0;
        int transItemNum = 0;
        List<Integer> transIds = new ArrayList<>();
        for (Tuple tuple:tupleSet){
            JSONObject object1 = JSONObject.parseObject(tuple.getElement());
            duration = duration + object1.getIntValue("duration");
            dataLength = dataLength + object1.getIntValue("dataLength");
            transItemNum = transItemNum + object1.getIntValue("transItemNum");
            transIds.add(object1.getInteger("transId"));
            transCount++;
        }
        object.put("duration",duration);
        object.put("transCount",transCount);
        object.put("dataLength",dataLength);
        object.put("transItemNum",transItemNum);
        object.put("startTime",formatter.format(min));
        object.put("end",formatter.format(max));
        object.put("transIds",transIds);

        return object;
    }

    @Override
    public Set<Tuple> getFtpFiles() {
        Set<Tuple> tupleSet = redisClient.zrangeWithScore(SYNC_FTP_FILE_INDEX,0,-1);

        return tupleSet;
    }

    @Override
    public Map<String, String> getTransTimer() {
        Map<String, String> anchor = redisClient.hgetAll(FTP_TRANS_DATA_TIMER);

        return anchor;
    }

    @Override
    public Set<Tuple> getSlicerFtp() {
        Set<Tuple> tupleSet = redisClient.zrangeWithScore(SYNC_LOG_FTP,0,-1);

        return tupleSet;
    }
}
